package com.example.teachdemo05;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class ImageSwitcherActivity extends AppCompatActivity {

    int[] imgIds = new int[]{
            R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
            R.mipmap.img04,R.mipmap.img05,R.mipmap.img06
    };
    ImageSwitcher iSwitcher;
    float sx,dx;
    int currentIndex = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_switcher);

        iSwitcher = findViewById(R.id.iSwitcher);

        iSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {

                ImageView imageView = new ImageView(ImageSwitcherActivity.this);

                imageView.setImageResource( imgIds[currentIndex]);

                return imageView;
            }
        });

        iSwitcher.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {


                  if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                      sx = motionEvent.getX();

                      return true;
                  }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                      dx = motionEvent.getX();

                      if(sx - dx > 10){
                          Log.v("msg:","left");
                          currentIndex = currentIndex -1;
                          //if(currentIndex < 0) currentIndex = 0;
                          if(currentIndex < 0) currentIndex = imgIds.length -1;
                          iSwitcher.setImageResource(imgIds[currentIndex]);
                      }

                      if(dx - sx > 10){
                          Log.v("msg:","right");
                          currentIndex = currentIndex + 1;
                          if (currentIndex == imgIds.length) currentIndex = 0;
                          iSwitcher.setImageResource(imgIds[currentIndex]);
                      }
                      return true;
                  }

                return false;
            }
        });
    }
}
